package site.liuming.truismcms.core.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import site.liuming.truismcms.core.auth.PermissionMeta;
import site.liuming.truismcms.core.log.LogResolver;
import site.liuming.truismcms.core.log.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LogInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private LogResolver logResolver;

    public LogInterceptor() {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Logger logger = method.getAnnotation(Logger.class);
            // 记录有 Logger 注解的访问记录
            if(logger != null) {
                PermissionMeta meta = method.getAnnotation(PermissionMeta.class);
                this.logResolver.handler(meta, logger, request, response);
            }
        }
    }
}
